﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Common;

namespace AccessToDataLibrary
{
    public partial class AccessToDataLibrary
    {
        public List<User> GetAllUsers()
        {
            List<User> users = new List<User>();
            DataRowCollection allusers = libraryDataSet.Users.Rows;

            foreach (UniversityLibraryDataSet.UsersRow userRow in allusers)
            {
                users.Add(new User (userRow.ID,userRow.Name,userRow.UserName,userRow.Password,userRow.IsAdmin));
            }
            return users;
        }
        public List<BorrowedCopie> GetAllBorrowedCopiesByUser(Guid userID)
        {
            List<BorrowedCopie> allBorrowedCopieByUser =
                new List<BorrowedCopie>();
            DataRow[] borrowedCopieByUser =
                libraryDataSet.Borrows.Select("UserID = '"+userID+"'");

            foreach (UniversityLibraryDataSet.BorrowsRow borRow in borrowedCopieByUser)
            {
                allBorrowedCopieByUser.Add(new BorrowedCopie(borRow.CopiesID, borRow.UserId,
                    borRow.BorrowDate, borRow.CopiesRow.ItemsRow.Name));
            }
            return allBorrowedCopieByUser;
        }
        public bool ReturnBooks(List<Guid> returnedItems)
        {
            foreach (Guid copieID in returnedItems)
            {
                try
                {
                    libraryDataSet.Borrows.FindByCopiesID(copieID).Delete();
                }
                catch
                {
                }
            }
            provider.UpdateAllData();
            return true;
        }
        public bool AddUser(User user)
        {
            try
            {
                libraryDataSet.Users.AddUsersRow(user.ID, user.Name,
                    user.UserName, user.Password, user.IsAdmin);

                provider.UpdateAllData();
            }
            catch
            {
                return false;
            }
            return true;

        }

        public User CheckUser(string userName,Guid password)
        {
            UniversityLibraryDataSet.UsersRow[] userRows =
             (UniversityLibraryDataSet.UsersRow[])   libraryDataSet.Users.Select("UserName = '" + userName + "' AND Password ='" + password + "'");

            if (userRows != null && userRows.Length > 0)
            {
                return new User(userRows[0].ID, userRows[0].Name, userRows[0].UserName,
                    userRows[0].Password, userRows[0].IsAdmin);
            }
            else
                return null;
        }
    }
}
